package com.heima.wemedia.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmService {
    @Override
    public ResponseResult login(WmUserDTO wmUserDTO) {
        if (StringUtils.isBlank(wmUserDTO.getName()) || StringUtils.isBlank(wmUserDTO.getPassword())) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空");
        }
        //查询用户是否存在
        WmUser user = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, wmUserDTO.getName()));
        if (user == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
        // 对比密码是否正确
        String inputPwd = DigestUtils.md5DigestAsHex((wmUserDTO.getPassword() + user.getSalt()).getBytes(StandardCharsets.UTF_8));
        if (!inputPwd.equals(user.getPassword())) {
            CustomException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
        }
        // 检查用户状态是否可用
        if (user.getStatus().intValue() != 9) {
            CustomException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        // 修改登录时间
        user.setCreatedTime(new Date());
        updateById(user);

        //颁发jwtToken,根据用户id生成token字符串
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        Map result = new HashMap();
        result.put("token",token);
        //user中存在密码和盐等敏感数据,不能直接放入
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(user,wmUserVO);
        result.put("user",wmUserVO );

        return ResponseResult.okResult(result);
    }
}
